const Koa = require("koa");
const KoaRouter = require("@koa/router");
const static = require("koa-static");

const app = new Koa();

app.use(static("./client"));

// 中间件
// app.use(async (ctx, next) => {
//   ctx.set("Access-Control-Allow-Origin", "*"); // 允许所有来源访问
//   // ctx.set(
//   //   "Access-Control-Allow-Origin",
//   //   "Accept,AcceptEncoding, Connection, Host, Origin"
//   // ); // 允许指定来源访问
//   // ctx.set("Access-Control-Allow-Credentials", "true"); // 允许携带凭证
//   // ctx.set("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
//   // 发起一个options 请求
//   if (ctx.method === "OPTIONS") {
//     ctx.status = 204;
//   } else {
//     await next();
//   }
// });

const userRouter = new KoaRouter({ prefix: "/users" });
userRouter.get("/list", (ctx, next) => {
  ctx.body = [
    { id: 1, name: "张三" },
    { id: 2, name: "李四" },
  ];
});

app.use(userRouter.routes());
app.use(userRouter.allowedMethods());

app.listen(8000, () => {
  console.log("服务器启动成功");
});
